using imitateMacQQ.WebApi.Configures;
using imitateMacQQ.WebApi.Domain.Login.register.Login.Entity;
using imitateMacQQ.WebApi.Domain.Login.register.Login.Interface;
using imitateMacQQ.WebApi.Domain.Login.register.Login.letter;
using imitateMacQQ.WebApi.Domain.Request.utils;
using imitateMacQQ.WebApi.Repository.EFCore.Model;

namespace imitateMacQQ.WebApi.Domain.Login.register.Login.Service;

public class RegisterNewUser : IRegisterFromInfoResult
{
    private readonly INLogHelper _logHelper;
    private readonly IRegisterTools _registerTools;

    public RegisterNewUser(IRegisterTools registerTools, INLogHelper logHelper)
    {
        _registerTools = registerTools;
        _logHelper = logHelper;
    }

    public Request<RegisterBackInfo> GetResult(NewRegisterUserInfo dto)
    {
        //验证
        try
        {
            using DataDbContext db = new DataDbContext();
            var info = db.PhoneCodes.FirstOrDefault(e => e.Phone == dto.Phone);
            if ((info is null || info.Code != dto.Code) && dto.Code == "0")
                throw new Exception("The verification code fails. Procedure");
            var infoUser = db.Users.Count(e => e.Phone == dto.Phone);
            if (infoUser > 2)
                throw new Exception("同一手机号只能注册3个账户！");
        }
        catch (Exception ex)
        {
            _logHelper.LogError(ex);
            return Request<RegisterBackInfo>.Ok(null!, false, ex.Message);
        }

        //注册
        var dao = new RegisterBackInfo();
        var success = true;
        if (_registerTools.RegisterCheckout(dto, out var str))
        {
            dao.Account = _registerTools.GenerateQqCode();
            dao.Text = str;
            UserInfoGetResultSaveSql(dto, dao.Account);
        }
        else
        {
            success = false;
            dao.Text = str;
        }

        return Request<RegisterBackInfo>.Ok(dao, success, str);
    }

    private void UserInfoGetResultSaveSql(NewRegisterUserInfo dto, string account)
    {
        using DataDbContext db = new();
        var info = db.PhoneCodes.FirstOrDefault(e => e.Phone == dto.Phone);
        if (info is not null)
            info.Code = "0";
        db.Users.Add(new User()
        {
            Account = account,
            Password = dto.Password,
            UserName = "ADMIN",
            Sex = "男",
            Phone = dto.Phone
        });
        db.SaveChanges();
    }
}